package com.fos.BluetoothStory.service;

import java.io.File;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

/**
 * 音乐播放器
 * @author fanxing 创建于 Oct 22, 2015
 */
public class PlaySongService extends Service implements OnErrorListener, OnPreparedListener, OnCompletionListener,
	PlayerStateListener{
	public static final String INTENT_PLAY_STATE = "com.fan.outsourcing.BluetoothStory.service.playState";//播放状态
	public static final String INTENT_PLAY_SONG = "com.fan.outsourcing.BluetoothStory.service.playFile";//播放
	public static final String INTENT_PLAY_ACTION = "com.fan.outsourcing.BluetoothStory.service.playAction";//播放上一个或下一个的动作
	public static final String STATE = "state";
	public static final String NAME_ACTION = "ACTION_NAME";//动作key
	public static final int NAME_ACTION_NEXT = 1;//下一首
	public static final int NAME_ACTION_UP = 0;//上一上
	public static final String BROAD_SONG = "song";//播放歌曲url的key
	private AudioManager audioManager;
	private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener;

	public class MyBinder extends Binder{
		public PlayerStateListener getListener(){
			return PlaySongService.this;
		};
	};
	
	private MyBinder myBinder = new MyBinder();
	private String mSongUrl;
	private MediaPlayer player;
	private Toast toast;
	private boolean isPrepared, isPlaying;
	/**电话状态*/
	private PhoneStateListener phoneStateListener = new PhoneStateListener(){
		public void onCallStateChanged(int state, String incomingNumber) {
			switch(state) {
	            case TelephonyManager.CALL_STATE_IDLE: //空闲
	            	if(isPrepared && !player.isPlaying()){
	            		goOnPlay();
	            	}
	                break;
	            case TelephonyManager.CALL_STATE_RINGING: //来电
	            	if(player.isPlaying())
	            		pausePaly();
	                break;
	            }
		};
	};
	/**播放数据来源*/
	private BroadcastReceiver orderReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			String song = intent.getStringExtra(BROAD_SONG);
			if(!TextUtils.isEmpty(song)){
				if(!song.equals(mSongUrl)){
					mSongUrl = song;
					prePlay();
				}else{
					if(isPlaying){
						pausePaly();
					}else{
						goOnPlay();
					}
				}
			}else if(TextUtils.isEmpty(song)){
				pausePaly();
			}
		};
	};
	private LocalBroadcastManager lbm;
	
	@Override
	public IBinder onBind(Intent intent) {
		return myBinder;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		audioManager.abandonAudioFocus(audioFocusChangeListener);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		lbm = LocalBroadcastManager.getInstance(this);
		initPlayer();
		initPhoneListener();
		initBroadcast();
		initAudioListenter();
	}

	/**播放焦点监听**/
	private void initAudioListenter(){
		audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
			@Override
			public void onAudioFocusChange(int focusChange) {
				if(focusChange != AudioManager.AUDIOFOCUS_GAIN){
					//失去焦点之后的操作
					if(isPlaying()){
						pausePaly();
					}
				}
			}
		};
	}
	
	/**播放文件变更*/
	private void initBroadcast(){
		lbm.registerReceiver(orderReceiver, new IntentFilter(INTENT_PLAY_SONG));
	}

	/**电话监听*/
	private void initPhoneListener() {
		//获取电话通讯服务
        TelephonyManager tpm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        //创建一个监听对象，监听电话状态改变事件
        tpm.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
	}

	/**初始化*/
	private void initPlayer() {
		if(player == null){
			player = new MediaPlayer();
			player.setOnErrorListener(this);
			player.setOnPreparedListener(this);
			player.setOnCompletionListener(this);
		}
	}
	
	/**准备播放*/
	private void prePlay(){
		File sFile = new File(mSongUrl);
		if(!sFile.exists() || !sFile.canRead())
			showToast("文件不存在");
		
		player.reset();
		try {
			player.setDataSource(mSongUrl);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("fan", e.toString());
		}
		isPrepared = false;
		isPlaying = false;
		player.prepareAsync();
	}
	
	private void broadPlayState(){
		Intent playState = new Intent(INTENT_PLAY_STATE);
		playState.putExtra(STATE, isPlaying);
		lbm.sendBroadcast(playState);
	}
	
	/**数据准备完可以播放*/
	@Override
	public void onPrepared(MediaPlayer mp) {
		isPrepared = true;
		int result = audioManager.requestAudioFocus(audioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
		if(result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED){
			mp.start();
			isPlaying = true;
		}else{
			isPlaying = false;
		}
		broadPlayState();
	}
	
	/**暂停*/
	private void pausePaly(){
		if(player!=null && player.isPlaying()){
			player.pause();
		}
		isPlaying = false;
		broadPlayState();
	}
	
	/**继续播放*/
	private void goOnPlay(){
		if(player!=null && !player.isPlaying()){
			if(isPrepared){
				int result = audioManager.requestAudioFocus(audioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
				if(result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED){
					isPlaying = true;
					player.start();
				}else{
					isPlaying = false;
				}
				broadPlayState();
			}else{
				prePlay();
			}
		}
	}
	
	/**播放指定位置*/
	private void playPosition(int msec){
		if(player!=null && isPrepared){
			player.seekTo(msec);
		}
	}

	/**播放发生异常*/
	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		Log.e("fan", "what=" + what + "; extra=" + extra);
		showToast("暂时无法播放");
		return false;
	}

	private void showToast(String msg){
		if(toast!=null){
			toast.setText(msg);
			toast.setDuration(Toast.LENGTH_SHORT);
		}else{
			toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
		}
		toast.show();
	}

	/**自动下一首*/
	@Override
	public void onCompletion(MediaPlayer mp) {
		isPlaying = false;
		Intent next = new Intent(INTENT_PLAY_ACTION);
		next.putExtra(NAME_ACTION, NAME_ACTION_NEXT);
		lbm.sendBroadcast(next);
	}
	
	@Override
	public boolean isPlaying() {
		if(player != null){
			isPlaying = player.isPlaying();
		}else{
			isPlaying = false;
		}

		Log.v("fan", ">>>>>>>>>>>>>>>isPlaying="+isPlaying);
		return isPlaying;
	}

	@Override
	public String getSongPath() {
		return mSongUrl;
	}
}
